package com.gobrs.async.core;

import com.gobrs.async.core.task.AsyncTask;

import java.util.*;

/**
 * 任务流
 * 任务总线负责任务处理流程
 */
public class TaskFlow {

    /**
     * 任务 -> 直接子任务组
     * 例如：AService->BService->FService
     * AService->BService
     * BService->FService
     * FService->null
     */
    private final IdentityHashMap<AsyncTask, List<AsyncTask>> denpendedTasks = new IdentityHashMap<>();

    /**
     * 收到任务后的处理
     * @param asyncTasks 异步任务集
     * @return 任务接受者
     */
    synchronized TaskReceive after(final AsyncTask... asyncTasks) {
        for (AsyncTask handler : asyncTasks) {
            if (!denpendedTasks.containsKey(handler)) {
                throw new IllegalStateException("asyncTask not begin command");
            }
        }
        return start(asyncTasks);
    }

    /**
     * 接受任务
     * @param asyncTasks 异步任务集
     * @return 任务接受者
     */
    synchronized TaskReceive start(AsyncTask... asyncTasks) {
        /**
         * 构建任务流
         */
        TaskReceive builder = new TaskReceive(this, Arrays.asList(asyncTasks));
        return builder;
    }

    /**
     * 开始任务接收
     */
    synchronized TaskReceive start(List<AsyncTask> asyncTasks) {
        /**
         * 构建任务流
         */
        TaskReceive builder = new TaskReceive(this, asyncTasks);
        return builder;
    }

    /**
     * 获取依赖任务
     */
    synchronized Map<AsyncTask, List<AsyncTask>> getDependsTasks() {
        return denpendedTasks;
    }

    /**
     * 添加任务依赖项
     */
    void addDependency(AsyncTask from, AsyncTask to) {
        if (!denpendedTasks.containsKey(from)) {
            denpendedTasks.put(from, new ArrayList<>(0));
        }
        if (to != null && !denpendedTasks.get(from).contains(to)) {
            denpendedTasks.get(from).add(to);
        }
    }

}
